import { NMTopoBaseCommand } from '@app-cad/environments/nextmesh/types/command';
import { useState } from 'react';
import { CommandDialog, pickedLineData } from '@amcax/base';

import { CommandFormWrapper } from '@app-cad/common/components/command-form';
import { PickInputForFocus } from '@app-cad/common/components/command-form/auto-focus/pick-input';
import { CommandFormFooter } from '@app-cad/common/components/command-form/footer';
import i18n from '@app-cad/common/utils/i18next';

import { Popover, Button, InputNumber } from 'antd';
import { DirectionGroup } from '../cmd-direction';
import { useCommand } from '@app-cad/common/hooks/useCommand';
import { documentV2 } from '@app-nextmesh/domain';
import { CommandLabeledItemWrapper } from '@app-base/common/components/command-form/item-wrapper';
import { getNormalsOrIds } from '../cmd-common/tools';
import { Vector3Tuple } from 'three-legacy';
import { PickInputValueType } from '@app-base/common/components/pick-input/types';
type DirectionType = {
  key: 0 | 1 | 2;
  title: string;
  show: boolean;
  vec: Vector3Tuple;
  num: number;
};
const args = {
  title: '选择方向',
  show: false,
  vec: null,
  num: 1,
};
export function Command({ onClose, title }) {
  const [sourceData, setSourceData] = useState<pickedLineData[]>([]);
  const [directionInfo, setDirectionInfo] = useState<DirectionType[]>([
    { key: 0, ...args },
    { key: 1, ...args },
    { key: 2, ...args },
  ]);

  const changeDirectionInfo = (item: Partial<DirectionType>) => {
    setDirectionInfo((state) => {
      return state.map((item1) => {
        if (item1.key === item.key) {
          return {
            ...item1,
            ...item,
          };
        }
        return item1;
      });
    });
  };
  useCommand('cmdArray', {
    onClose,
  });

  const onSourcePickData = (sourceArr) => {
    setSourceData(sourceArr);
  };
  const isValid = () => {
    return sourceData.length > 0;
  };
  const handleSubmit = async () => {
    if (!isValid()) {
      return;
    }
    const ids = getNormalsOrIds(sourceData, 'id').map((item) => item.id);
    const fil = directionInfo.filter((item) => item?.vec);
    const params = {
      mode: 'array',
      source: ids,
      param: fil.map((item) => item.num),
      relyOn: fil.map((item) => item.vec),
    };
    await documentV2.transform(params);
    onClose();
  };

  const onDirectionData = (data, item: DirectionType) => {
    changeDirectionInfo({
      ...item,
      vec: data?.directionVec,
      title: data?.directionText,
      show: data?.directionVisible,
    });
  };
  const isDisabled = (ind, state: 'popover' | 'input' = 'input') => {
    if (state === 'popover') {
      return !isValid() || (ind !== 0 && !directionInfo[ind - 1]?.vec);
    } else {
      return !isValid() || !directionInfo[ind]?.vec;
    }
  };
  return (
    <CommandDialog
      title={title}
      placement='topLeft'
      onClose={onClose}
    >
      <CommandFormWrapper>
        <PickInputForFocus
          autoFocus
          controlled
          allowPickType={[
            PickInputValueType.Vertex,
            PickInputValueType.Curve,
            PickInputValueType.Surface,
          ]}
          onPick={onSourcePickData}
          value={sourceData}
          placeholder='请选择点/线/面'
        />
        {directionInfo.map((tiem) => (
          <Popover
            getPopupContainer={() => document.querySelector('#app-cad_root')}
            trigger='click'
            title='方向选择'
            open={tiem.show}
            content={
              <DirectionGroup
                onDirectionSubmit={(data) => onDirectionData(data, tiem)}
              />
            }
          >
            <Button
              disabled={isDisabled(tiem.key, 'popover')}
              onClick={() => changeDirectionInfo({ key: tiem.key, show: true })}
            >
              {tiem.title}
            </Button>
          </Popover>
        ))}
        {directionInfo.map((item) => (
          <CommandLabeledItemWrapper
            textClassName='text-reset'
            label={`数量${item.key + 1}`}
          >
            <InputNumber
              disabled={isDisabled(item.key)}
              defaultValue={1}
              onChange={(val: number) => {
                changeDirectionInfo({ num: val, key: item.key });
              }}
            />
          </CommandLabeledItemWrapper>
        ))}
        <CommandFormFooter
          onClose={onClose}
          onSubmit={handleSubmit}
          submitText='完成'
          isSubmitDisabled={!isValid()}
        />
      </CommandFormWrapper>
    </CommandDialog>
  );
}

export const cmdTopoArray: NMTopoBaseCommand = {
  id: 'cmdTopoArray',
  label: 'command.topo.array',
  icon: 'commands/feature/array',
  create: function (label: string, onClose: () => void) {
    return (
      <Command
        title={i18n.t(label)}
        onClose={onClose}
      />
    );
  },
};
